package mylibrary.encoding;

import java.nio.charset.Charset;

public class Test3 {

	public static void main(String[] args) throws Exception {
		
		System.out.println(Charset.defaultCharset());
		
		String name = "I am 君山";
		System.out.println("Default " + byteArray2Hex(name.getBytes()));
		
		
		byte[] iso8859 = name.getBytes("ISO-8859-1");
		System.out.println("ISO-8859-1: " + byteArray2Hex(iso8859));

		byte[] gb2312 = name.getBytes("gb2312");
		System.out.println("GB2312: " + byteArray2Hex(gb2312));
		
		byte[] gbk = name.getBytes("GBK");
		System.out.println("GBK: " + byteArray2Hex(gbk));

		byte[] utf16 = name.getBytes("UTF-16BE");
		System.out.println("UTF-16: " + byteArray2Hex(utf16));

		byte[] utf8 = name.getBytes("UTF-8");
		System.out.println("UTF-8: " + byteArray2Hex(utf8));
	}
	
	public static String byteArray2Hex(byte[] b) {
		StringBuffer sb = new StringBuffer();
		for(int i=0; i<b.length; i++) {
			int j = b[i];
			if(j<0) {
				j+=256;
			}
			sb.append(hex(j/16));
			sb.append(hex(j%16));
		}
		return sb.toString();
	}
	
	public static char hex(int i) {
		switch(i) {
		case 10: return 'a';
		case 11: return 'b';
		case 12: return 'c';
		case 13: return 'd';
		case 14: return 'e';
		case 15: return 'f';
		
		default: return (char) (i+48);
		}
	}
}

